package com.apkcore.core.ui.recyclerview

import android.annotation.SuppressLint
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding

abstract class RVAdapter<T, VB : ViewBinding>(
    private val inflate: (LayoutInflater, ViewGroup, Boolean) -> VB
) : RecyclerView.Adapter<RVAdapter.BaseViewHolder<VB>>() {

    private val items: MutableList<T> = mutableListOf()
    private var itemClickListener: ((View, Int, T) -> Unit)? = null
    private var itemLongClickListener: ((View, Int, T) -> Unit)? = null

    abstract fun bind(cBinding: VB, item: T, position: Int)
    open fun initView(cBinding: VB, itemView: View) {}

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder<VB> {
        val binding = inflate(LayoutInflater.from(parent.context), parent, false)
        val viewHolder = BaseViewHolder(binding)
        initView(binding, viewHolder.itemView)
        itemClickListener?.let {
            viewHolder.itemView.setOnClickListener { view ->
                val position = viewHolder.adapterPosition
                if (position != RecyclerView.NO_POSITION) {
                    it.invoke(view, position, items[position])
                }
            }
        }
        itemLongClickListener?.let {
            viewHolder.itemView.setOnLongClickListener { view ->
                val position = viewHolder.adapterPosition
                if (position != RecyclerView.NO_POSITION) {
                    it.invoke(view, position, items[position])
                    return@setOnLongClickListener true
                }
                false
            }
        }
        return viewHolder
    }

    override fun onBindViewHolder(holder: BaseViewHolder<VB>, position: Int) {
        bind(holder.binding, items[position], position)
    }

    override fun getItemCount(): Int = items.size

    @SuppressLint("NotifyDataSetChanged")
    fun setItems(newItems: List<T>) {
        items.clear()
        items.addAll(newItems)
        notifyDataSetChanged()
    }
    fun addItem(t: T) {
        items.add(t)
//        notifyItemInserted(items.size)
        notifyDataSetChanged()
    }

    fun getItems(): List<T> {
        return items
    }

    fun clearList() {
        items.clear()
        notifyDataSetChanged()
    }

    fun removePosition(position: Int) {
        items.removeAt(position)
        notifyDataSetChanged()
    }

    fun setOnItemClickListener(listener: (view: View, position: Int, item: T) -> Unit) {
        itemClickListener = listener
    }

    fun setOnItemLongClickListener(listener: (view: View, position: Int, item: T) -> Unit) {
        itemLongClickListener = listener
    }

    class BaseViewHolder<VB : ViewBinding>(val binding: VB) :
        RecyclerView.ViewHolder(binding.root)
}
